package com.movieproject.daos.imp;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.movieproject.daos.InventoryDAO;
import com.movieproject.dataobjects.InventoryItem;
import com.movieproject.dataobjects.Movie;

@Service
public class InventoryDAOImp implements InventoryDAO {
	@Autowired
	private SessionFactory sessionFactory;

	@Override
	public List<InventoryItem> getAllItems() {
		Query query = sessionFactory.getCurrentSession().createQuery("from InventoryItem");
		List<?> l = query.list(); // query returns a raw list. 
		ArrayList<InventoryItem> inventoryList = new ArrayList<InventoryItem>();
		for(Object o : l) {	// objects in list must be cast individually	
			inventoryList.add((InventoryItem) o);
		}
		return inventoryList;
	}

	@Override
	public List<InventoryItem> getItemsByMovie(Movie movie) {
		Query query = sessionFactory.getCurrentSession().createQuery("from InventoryItem where MovieID = :m");
		query.setParameter("m", movie.getMovieID());
		List<?> l = query.list(); // query returns a raw list. 
		ArrayList<InventoryItem> inventoryList = new ArrayList<InventoryItem>();
		for(Object o : l) {	// objects in list must be cast individually	
			inventoryList.add((InventoryItem) o);
		}
		return inventoryList;
	}

	//shows the inventory items that are currently in stock
	@Override
	public List<InventoryItem> getItemsInStock() {
		Query query = sessionFactory.getCurrentSession().createQuery("from InventoryItem where Instock = 1");
		List<?> l = query.list(); // query returns a raw list. 
		ArrayList<InventoryItem> inventoryList = new ArrayList<InventoryItem>();
		for(Object o : l) {	// objects in list must be cast individually	
			inventoryList.add((InventoryItem) o);
		}
		return inventoryList;
	}

	@Override
	public InventoryItem getItem(int inventoryID) {
		return (InventoryItem) sessionFactory.getCurrentSession().get(InventoryItem.class, inventoryID);
	}

	@Override
	public void updateItem(InventoryItem item) {
		sessionFactory.getCurrentSession().merge(item);
	}

	@Override
	public void deleteItem(InventoryItem item) {
		sessionFactory.getCurrentSession().delete(item);
	}

}
